<?php
namespace app\common\service\product;

use think\facade\Db;
use app\api\model\Send;


/**
 * 消息推送
 * Class NoticeService
 * @package app\common\service\product
 */
class NoticeService
{
    /**
     * 订单支付成功通知
     * @param $order_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderPaySuccessNotice($order_id){
        $order = Db::table('evt_customer_product_order')->where('id', $order_id)->find();
        $roomInfo = Db::table('evt_mini_room_list')->field('admin_id,room_name')->where(['id' => $order['store_id']])->find();
        $wxapp = Db::table('evt_mini_match')->where(['wxapp_id' => $roomInfo['admin_id']])->find();
        $wxapp_id = $wxapp['id'];
        $token = $this->token($wxapp_id);
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $token;

        $name = '';
        $orderProductList = Db::table('evt_customer_product_order_product')->field('product_name,sku_name')->where('order_id', $order_id)->select();
        foreach ($orderProductList as $k => $orderProduct){
            if ($k == 0) {
                $name.= $orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            } else {
                $name.= ','.$orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            }
        }
        $names = sub_str($name,0,17);

        if ($order['payment_type'] == 1) {
            $type = "微信支付,实付" . $order['pay_money'].'元';
        }
        if ($order['payment_type'] == 2) {
            $type = "余额支付,金额为" . $order['pay_money'].'元';
        }
        $info = Db::table('evt_mini_admin_remind')->where(['admin_id' => $roomInfo['admin_id']])->find();
        $user = Db::table('evt_mini_member_list')->where('id', $order['user_id'])->find();
        // 查询是否通知
        if ($info['is_book'] == 1) {
            $data[0]['template_id'] = $info['make_id'];
            if ($info['make_id']) {
                $data['touser'] = $user['openid'];
                $data['template_id'] = $info['make_id'];
                $data['page'] = "pages2/market/orderList";
                $time = date('Y-m-d H:i', $order['create_time']);
                $list = array(
                    'thing1' => array('value' => $roomInfo['room_name']),
                    'number2' => array('value' => $order['order_sn']),
                    'thing11' => array('value' => $names),
                    'time5' => array('value' => $time),
                    'thing4' => array('value' => $type)
                );
                $list = json_encode($list);
                $data['data'] = json_decode($list);
                $this->curl($url, 'POST', json_encode($data));
            }
        }

        //商家通知
        $send_message['url'] = '';
        $send_message['first']['value'] = '用户' . $user['nickname'] . $user['mobile'] . ',购买'.$roomInfo['room_name'].'商城商品成功';
        $send_message['keyword1']['value'] = $roomInfo['room_name'];
        $send_message['keyword2']['value'] = $order['order_sn'];
        $send_message['keyword3']['value'] = $name;
        $send_message['keyword4']['value'] = $type;
        $send_message['keyword5']['value'] = date('Y-m-d H:i:s', time());
        Send::newtoyuyue($user['admin_id'], $send_message);
    }


    /**
     * 同城配送通知
     * @param $order_id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function localDeliveryNotice($order_id){
        $order = Db::table('evt_customer_product_order')->where('id', $order_id)->find();
        $roomInfo = Db::table('evt_mini_room_list')->field('admin_id,room_name')->where(['id' => $order['store_id']])->find();

        $name = '';
        $orderProductList = Db::table('evt_customer_product_order_product')->field('product_name,sku_name')->where('order_id', $order_id)->select();
        foreach ($orderProductList as $k => $orderProduct){ //上述错误，可能是因为data.thing的内容过长，超过了20个字限制。（1个汉字也只算1个字）
            if ($k == 0) {
                $name.= $orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            } else {
                $name.= ','.$orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            }
        }
        $name = sub_str($name,0,17);
        $wxapp = Db::table('evt_mini_match')->where(['wxapp_id' => $roomInfo['admin_id']])->find();
        $wxapp_id = $wxapp['id'];
        $token = $this->token($wxapp_id);
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $token;

        $info = Db::table('evt_mini_admin_remind')->where(['admin_id' => $roomInfo['admin_id']])->find();
        $user = Db::table('evt_mini_member_list')->where('id', $order['user_id'])->find();
        // 查询是否通知
        if ($info['is_book'] == 1) {
            $data['page'] = "pages2/market/orderList";
            $data['touser'] = $user['openid'];
            $data['template_id'] = $info['tui_id'];
            $time = date('Y-m-d H:i', time());
            $list = array(
                'thing14' => array('value' => $roomInfo['room_name']),
                'thing1' => array('value' => "$name"),
                'phrase2' => array('value' => '配送中'),
                'date10' => array('value' => $time),
                'thing5' => array('value' => '商城订单,同城配送中')
            );
            $list = json_encode($list);
            $data['data'] = json_decode($list);
            $this->curl($url, 'POST', json_encode($data));
        }

        $send_message['url'] = '';
        $send_message['first']['value'] = "用户".$user['nickname'] . $user['mobile']. '在'.$roomInfo['room_name'].' 商城： 订单开始同城配送';
        $send_message['keyword1']['value'] = $order['order_sn'];
        $send_message['keyword2']['value'] = $user['nickname'] . $user['mobile'];
        $send_message['keyword3']['value'] = '同城配送';
        $send_message['keyword4']['value'] = date('Y-m-d H:i:s', time());
        $send_message['keyword5']['value'] = $name.' ,同城配送中,订单号:'.$order['order_sn'];
        Send::addyuyue($user['admin_id'], $send_message);
    }



    /**
     * 快递配送通知
     * @param $order_id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function expressDeliveryNotice($order_id){
        $order = Db::table('evt_customer_product_order')->where('id', $order_id)->find();
        $roomInfo = Db::table('evt_mini_room_list')->field('admin_id,room_name')->where(['id' => $order['store_id']])->find();

        $name = '';
        $orderProductList = Db::table('evt_customer_product_order_product')->field('product_name,sku_name')->where('order_id', $order_id)->select();
        foreach ($orderProductList as $k => $orderProduct){ //上述错误，可能是因为data.thing的内容过长，超过了20个字限制。（1个汉字也只算1个字）
            if ($k == 0) {
                $name.= $orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            } else {
                $name.= ','.$orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            }
        }
        $names = sub_str($name,0,17);
        $wxapp = Db::table('evt_mini_match')->where(['wxapp_id' => $roomInfo['admin_id']])->find();
        $wxapp_id = $wxapp['id'];
        $token = $this->token($wxapp_id);
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $token;

        $info = Db::table('evt_mini_admin_remind')->where(['admin_id' => $roomInfo['admin_id']])->find();
        $user = Db::table('evt_mini_member_list')->where('id', $order['user_id'])->find();
        // 查询是否通知
        if ($info['is_book'] == 1) {
            $data['page'] = "pages2/market/orderList";
            $data['touser'] = $user['openid'];
            $data['template_id'] = $info['tui_id'];
            $time = date('Y-m-d H:i', time());
            $list = array(
                'thing14' => array('value' => $roomInfo['room_name']),
                'thing1' => array('value' => "$names"),
                'phrase2' => array('value' => '已发货'),
                'date10' => array('value' => $time),
                'thing5' => array('value' => '商城订单,已发货')
            );
            $list = json_encode($list);
            $data['data'] = json_decode($list);
            $this->curl($url, 'POST', json_encode($data));
        }

        $send_message['url'] = '';
        $send_message['first']['value'] = "用户".$user['nickname'] . $user['mobile']. '在'.$roomInfo['room_name'].' 商城： 订单开始快递配送';
        $send_message['keyword1']['value'] = $order['order_sn'];
        $send_message['keyword2']['value'] = $user['nickname'] . $user['mobile'];
        $send_message['keyword3']['value'] = '已发货';
        $send_message['keyword4']['value'] = date('Y-m-d H:i:s', time());
        $send_message['keyword5']['value'] = $name.' ,商城订单,已发货';
        Send::addyuyue($user['admin_id'], $send_message);
    }


    //售后申请通知
    public function afterSalesNotice($order_id){
        $order = Db::table('evt_customer_product_order')->where('id', $order_id)->find();
        $roomInfo = Db::table('evt_mini_room_list')->field('admin_id,room_name')->where(['id' => $order['store_id']])->find();
        $user = Db::table('evt_mini_member_list')->where('id', $order['user_id'])->find();

        $name = '';
        $orderProductList = Db::table('evt_customer_product_order_product')->field('product_name,sku_name')->where('order_id', $order_id)->select();
        foreach ($orderProductList as $k => $orderProduct){
            if ($k == 0) {
                $name.= $orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            } else {
                $name.= ','.$orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            }
        }
        //$name = sub_str($name,0,17);

        $send_message['url'] = '';
        $send_message['first']['value'] = "用户".$user['nickname'] . $user['mobile']. '在'.$roomInfo['room_name'].' 商城： 支付订单申请退款';
        $send_message['keyword1']['value'] = $order['order_sn'];
        $send_message['keyword2']['value'] = $user['nickname'] . $user['mobile'];
        $send_message['keyword3']['value'] = '已付款,申请退款';
        $send_message['keyword4']['value'] = date('Y-m-d H:i:s', time());
        $send_message['keyword5']['value'] =  $name.' ,申请订单退款';
        Send::addyuyue($user['admin_id'], $send_message);
    }

    //确认收货通知
    public function confirmReceiptNotice($order_id){
        $order = Db::table('evt_customer_product_order')->where('id', $order_id)->find();
        $roomInfo = Db::table('evt_mini_room_list')->field('admin_id,room_name')->where(['id' => $order['store_id']])->find();
        $user = Db::table('evt_mini_member_list')->where('id', $order['user_id'])->find();

        $name = '';
        $orderProductList = Db::table('evt_customer_product_order_product')->field('product_name,sku_name')->where('order_id', $order_id)->select();
        foreach ($orderProductList as $k => $orderProduct){
            if ($k == 0) {
                $name.= $orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            } else {
                $name.= ','.$orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            }
        }
        //$name = sub_str($name,0,17);
        $send_message['url'] = '';
        $send_message['first']['value'] = "用户".$user['nickname'] . $user['mobile']. '在'.$roomInfo['room_name'].' 商城： 订单确认收货';
        $send_message['keyword1']['value'] = $order['order_sn'];
        $send_message['keyword2']['value'] = $user['nickname'] . $user['mobile'];
        $send_message['keyword3']['value'] = '确认收货';
        $send_message['keyword4']['value'] = date('Y-m-d H:i:s', time());
        $send_message['keyword5']['value'] =  $name.' ,收货成功';
        Send::addyuyue($user['admin_id'], $send_message);
    }
    
    
      //提醒发货通知
    public function remindOrderNotice($order_id){
        $order = Db::table('evt_customer_product_order')->where('id', $order_id)->find();
        $roomInfo = Db::table('evt_mini_room_list')->field('admin_id,room_name')->where(['id' => $order['store_id']])->find();
        $user = Db::table('evt_mini_member_list')->where('id', $order['user_id'])->find();

        $name = '';
        $orderProductList = Db::table('evt_customer_product_order_product')->field('product_name,sku_name')->where('order_id', $order_id)->select();
        foreach ($orderProductList as $k => $orderProduct){
            if ($k == 0) {
                $name.= $orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            } else {
                $name.= ','.$orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            }
        }
        //$name = sub_str($name,0,17);
        $send_message['url'] = '';
        $send_message['first']['value'] = "用户".$user['nickname'] . $user['mobile']. '在'.$roomInfo['room_name'].' 商城： 订单发货提醒';
        $send_message['keyword1']['value'] = $order['order_sn'];
        $send_message['keyword2']['value'] = $user['nickname'] . $user['mobile'];
        $send_message['keyword3']['value'] = '未发货,请尽快发货';
        $send_message['keyword4']['value'] = date('Y-m-d H:i:s', time());
        $send_message['keyword5']['value'] =  $name.' ,发货提醒';
        Send::addyuyue($user['admin_id'], $send_message);
    }


    //取消售后申请通知
    public function cancelAfterSalesNotice($order_id){
        $order = Db::table('evt_customer_product_order')->where('id', $order_id)->find();
        $roomInfo = Db::table('evt_mini_room_list')->field('admin_id,room_name')->where(['id' => $order['store_id']])->find();
        $user = Db::table('evt_mini_member_list')->where('id', $order['user_id'])->find();

        $name = '';
        $orderProductList = Db::table('evt_customer_product_order_product')->field('product_name,sku_name')->where('order_id', $order_id)->select();
        foreach ($orderProductList as $k => $orderProduct){
            if ($k == 0) {
                $name.= $orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            } else {
                $name.= ','.$orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            }
        }
        //$name = sub_str($name,0,17);

        $send_message['url'] = '';
        $send_message['first']['value'] = "用户".$user['nickname'] . $user['mobile']. '在'.$roomInfo['room_name'].' 商城： 申请售后订单撤销';
        $send_message['keyword1']['value'] = $order['order_sn'];
        $send_message['keyword2']['value'] = $user['nickname'] . $user['mobile'];
        $send_message['keyword3']['value'] = '已付款,已取消订申请退';
        $send_message['keyword4']['value'] = date('Y-m-d H:i:s', time());
        $send_message['keyword5']['value'] = $name.' ,取消订单售后申请';
        Send::addyuyue($user['admin_id'], $send_message);
    }






    /**
     * 订单超时通知
     * @param $order_id
     */
    public function overtimeNotice($order_id){
        $order = Db::table('evt_customer_product_order')->where('id', $order_id)->find();
        $roomInfo = Db::table('evt_mini_room_list')->field('admin_id,room_name')->where(['id' => $order['store_id']])->find();
        $wxapp = Db::table('evt_mini_match')->where(['wxapp_id' => $roomInfo['admin_id']])->find();
        $wxapp_id = $wxapp['id'];
        $token = $this->token($wxapp_id);
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $token;

        $name = '';
        $orderProductList = Db::table('evt_customer_product_order_product')->field('product_name,sku_name')->where('order_id', $order_id)->select();
        foreach ($orderProductList as $k => $orderProduct){
            if ($k == 0) {
                $name.= $orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            } else {
                $name.= ','.$orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            }
        }
        $names = sub_str($name,0,17);

        $info = Db::table('evt_mini_admin_remind')->where(['admin_id' => $roomInfo['admin_id']])->find();
        $user = Db::table('evt_mini_member_list')->where('id', $order['user_id'])->find();
        // 查询是否通知
        if ($info['is_book'] == 1) {
            $data['page'] = "pages2/market/orderList";
            $data['touser'] = $user['openid'];
            $data['template_id'] = $info['tui_id'];

            $time = date('Y-m-d H:i', time());
            $list = array(
                'thing14' => array('value' => $roomInfo['room_name']),
                'thing1' => array('value' => $names),
                'phrase2' => array('value' => '已取消'),
                'date10' => array('value' => $time),
                'thing5' => array('value' => '商城商品下单,已超时取消')
            );
            $list = json_encode($list);
            $data['data'] = json_decode($list);
            $this->curl($url, 'POST', json_encode($data));
        }
        $send_message['url'] = '';
        $send_message['first']['value'] = "用户".$user['nickname'] . $user['mobile']. '在'.$roomInfo['room_name'].' 商城： 订单未支付，已超时自动取消';
        $send_message['keyword1']['value'] = $order['order_sn'];
        $send_message['keyword2']['value'] = $user['nickname'] . $user['mobile'];
        $send_message['keyword3']['value'] = '已取消';
        $send_message['keyword4']['value'] = date('Y-m-d H:i:s', time());
        $send_message['keyword5']['value'] = $name.', 已超时自动取消';
        Send::addyuyue($user['admin_id'], $send_message);

    }


    /**
     * 退款成功通知
     * @param $order_id
     * @param $refundPrice
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function refundSuccessNotice($order_id, $refundPrice){
        $order = Db::table('evt_customer_product_order')->where('id', $order_id)->find();
        $roomInfo = Db::table('evt_mini_room_list')->field('admin_id,room_name')->where(['id' => $order['store_id']])->find();
        $wxapp = Db::table('evt_mini_match')->where(['wxapp_id' => $roomInfo['admin_id']])->find();
        $wxapp_id = $wxapp['id'];
        $token = $this->token($wxapp_id);
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $token;

        $name = '';
        $orderProductList = Db::table('evt_customer_product_order_product')->field('product_name,sku_name')->where('order_id', $order_id)->select();
        foreach ($orderProductList as $k => $orderProduct){
            if ($k == 0) {
                $name.= $orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            } else {
                $name.= ','.$orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            }
        }
        $names = sub_str($name,0,17);

        if ($order['payment_type'] == 1) {
            $type = "已退订,退款金额" . $refundPrice.'元, 退到微信';
            $types = "退款成功，退款金额" . $refundPrice.'元, 退到微信';
        }
        if ($order['payment_type'] == 2) {
            $type =  "已退订,退款金额" . $refundPrice.'元, 退到余额';
            $types =  "退款成功，退款金额" . $refundPrice.'元, 退到余额';
        }
        $info = Db::table('evt_mini_admin_remind')->where(['admin_id' => $roomInfo['admin_id']])->find();
        $user = Db::table('evt_mini_member_list')->where('id', $order['user_id'])->find();
        // 查询是否通知
        if ($info['is_book'] == 1) {
            $data['page'] = "pages2/market/orderList";
            $data['touser'] = $user['openid'];
            $data['template_id'] = $info['tui_id'];

            $time = date('Y-m-d H:i', time());
            $list = array(
                'thing14' => array('value' => $roomInfo['room_name']),
                'thing1' => array('value' => $names),
                'phrase2' => array('value' => '退款成功'),
                'date10' => array('value' => $time),
                'thing5' => array('value' => $type)
            );
            $list = json_encode($list);
            $data['data'] = json_decode($list);
            $this->curl($url, 'POST', json_encode($data));
        }

        $send_message = [];
        $send_message['url'] = '';
        $send_message['first']['value'] = "用户".$user['nickname'] . $user['mobile']. '在'.$roomInfo['room_name'].' 商城： 支付订单已审核';
        $send_message['keyword1']['value'] = $order['order_sn'];
        $send_message['keyword2']['value'] = $user['nickname'] . $user['mobile'];
        $send_message['keyword3']['value'] = $types;
        $send_message['keyword4']['value'] = date('Y-m-d H:i:s', time());
        $send_message['keyword5']['value'] = $name.' ,退款成功';
        Send::addyuyue($user['admin_id'], $send_message);
    }



    /**
     * 退款拒绝通知
     * @param $order_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function refundRefuseNotice($order_id){
        $order = Db::table('evt_customer_product_order')->where('id', $order_id)->find();
        $roomInfo = Db::table('evt_mini_room_list')->field('admin_id,room_name')->where(['id' => $order['store_id']])->find();
        $wxapp = Db::table('evt_mini_match')->where(['wxapp_id' => $roomInfo['admin_id']])->find();
        $wxapp_id = $wxapp['id'];
        $token = $this->token($wxapp_id);
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $token;

        $name = '';
        $orderProductList = Db::table('evt_customer_product_order_product')->field('product_name,sku_name')->where('order_id', $order_id)->select();
        foreach ($orderProductList as $k => $orderProduct){
            if ($k == 0) {
                $name.= $orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            } else {
                $name.= ','.$orderProduct['product_name'].'('.str_replace(',',';',$orderProduct['sku_name']).')';
            }
        }
        $names = sub_str($name,0,17);

        $info = Db::table('evt_mini_admin_remind')->where(['admin_id' => $roomInfo['admin_id']])->find();
        $user = Db::table('evt_mini_member_list')->where('id', $order['user_id'])->find();
        // 查询是否通知
        if ($info['is_book'] == 1) {
            $data['page'] = "pages2/market/orderList";
            $data['touser'] = $user['openid'];
            $data['template_id'] = $info['tui_id'];
            $time = date('Y-m-d H:i', time());
            $list = array(
                'thing14' => array('value' => $roomInfo['room_name']),
                'thing1' => array('value' => $names),
                'phrase2' => array('value' => '退款失败'),
                'date10' => array('value' => $time),
                'thing5' => array('value' => '商家已拒绝，感谢您的使用')
            );
            $list = json_encode($list);
            $data['data'] = json_decode($list);
            $this->curl($url, 'POST', json_encode($data));
        }

        $send_message['url'] = '';
        $send_message['first']['value'] = "用户".$user['nickname'] . $user['mobile']. '在'.$roomInfo['room_name'].' 商城： 支付订单已审核';
        $send_message['keyword1']['value'] = $order['order_sn'];
        $send_message['keyword2']['value'] = $user['nickname'] . $user['mobile'];
        $send_message['keyword3']['value'] = '商家已拒绝，退款失败';
        $send_message['keyword4']['value'] = date('Y-m-d H:i:s', time());
        $send_message['keyword5']['value'] = $name.' ,退款失败';
        Send::addyuyue($user['admin_id'], $send_message);
    }

    /**
     * 通知
     * @param $wxapp_id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function token($wxapp_id)
    {
        $wxapp = Db::table('evt_mini_match')->where(['id' => $wxapp_id])->find();

        if ($wxapp['token'] == "") {
            $appid = $wxapp['app_id'];
            $app_secret = $wxapp['key'];

            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$app_secret}";
            $token = $this->curl($url, 'get', '');

            // 记录并保存
            $data = array(
                'token' => $token['access_token'],
                'end_token_time' => time() + 7200
            );
            Db::table('evt_mini_match')->where(['id' => $wxapp_id])->update($data);

            return $token['access_token'];
        } elseif ($wxapp['end_token_time'] < time()) {

            $appid = $wxapp['app_id'];
            $app_secret = $wxapp['key'];
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$app_secret}";

            $token = $this->curl($url, 'get', '');
            // 记录并保存
            $data = array(
                'token' => $token['access_token'],
                'end_token_time' => time() + 7200
            );

            if (Db::table('evt_mini_match')->where(['id' => $wxapp_id])->update($data)) {
                return $token['access_token'];
            }


        } else {
            return $wxapp['token'];
        }

    }

    /**
     * 请求
     * @param $url
     * @param $method
     * @param $params
     * @return mixed
     */
    private function curl($url, $method, $params)
    {

        //初始化CURL句柄
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);//设置请求的URL
        #curl_setopt($curl, CURLOPT_HEADER, false);// 不要http header 加快效率
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //设为TRUE把curl_exec()结果转化为字串，而不是直接输出
        //SSL验证
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);    // https请求时要设置为false 不验证证书和hosts  FALSE 禁止 cURL 验证对等证书（peer's certificate）, 自cURL 7.10开始默认为 TRUE。从 cURL 7.10开始默认绑定安装。
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);//检查服务器SSL证书中是否存在一个公用名(common name)。

        $header[] = "Content-Type:application/json;charset=utf-8";
        if (!empty($header)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);//设置 HTTP 头字段的数组。格式： array('Content-type: text/plain', 'Content-length: 100')
        }
        //请求时间
        $timeout = 30;
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);//设置连接等待时间

        //不同请求方法的数据提交
        switch ($method) {
            case "GET" :
                curl_setopt($curl, CURLOPT_HTTPGET, true);//TRUE 时会设置 HTTP 的 method 为 GET，由于默认是 GET，所以只有 method 被修改时才需要这个选项。
                break;
            case "POST":
                if (is_array($params)) {
                    $params = json_encode($params, 320);
                }
                #curl_setopt($curl, CURLOPT_POST,true);//TRUE 时会发送 POST 请求，类型为：application/x-www-form-urlencoded，是 HTML 表单提交时最常见的一种。
                #curl_setopt($curl, CURLOPT_NOBODY, true);//TRUE 时将不输出 BODY 部分。同时 Mehtod 变成了 HEAD。修改为 FALSE 时不会变成 GET。
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");//HTTP 请求时，使用自定义的 Method 来代替"GET"或"HEAD"。对 "DELETE" 或者其他更隐蔽的 HTTP 请求有用。 有效值如 "GET"，"POST"，"CONNECT"等等；
                //设置提交的信息
                curl_setopt($curl, CURLOPT_POSTFIELDS, $params);//全部数据使用HTTP协议中的 "POST" 操作来发送。
                break;
            case "PUT" :
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
                curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params, 320));
                break;
            case "DELETE":
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
                curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
                break;
        }

        $data = curl_exec($curl);//执行预定义的CURL


        curl_getinfo($curl, CURLINFO_HTTP_CODE);//获取http返回值,最后一个收到的HTTP代码
        curl_close($curl);//关闭cURL会话
        $res = json_decode($data, true);


        return $res;
    }

}